package cur.nature.admin.controller;

import cur.nature.admin.service.Admin_UserService;
import cur.nature.admin.common.log.LogTaskHelper;
import cur.nature.framework.mvc.auth.LoginUser;
import cur.nature.framework.mvc.base.BaseAPI;
import cur.nature.framework.mvc.crud.CrudController;
import cur.nature.tinyorm.core.bean.PageBean;
import cur.nature.admin.model.vo.Admin_UserVO;
import cur.nature.framework.mvc.http.ResponseObject;
import cur.nature.framework.core.thread.MyThreadLocal;
import cur.nature.framework.core.util.JWTUtil;
import cur.nature.framework.core.util.JsonUtil;
import cur.nature.framework.core.util.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户信息 Controller
 * 作者：Auto Generator By wujian
 * 生成日期：2023-07-10 21:42:14
 */
@Tag(name = "用户信息 接口")
@RestController
@RequestMapping("admin/v1/api/Admin_User")
public class Admin_UserController extends CrudController<Admin_UserService> {
    public Admin_UserController(Admin_UserService baseService) {
        super(baseService);
    }

    @Autowired
    private LogTaskHelper logTaskHelper;

    @Operation(summary = "查询 用户信息")
    @PostMapping("/list")
    public PageBean<Admin_UserVO> list(@Valid @RequestBody Admin_UserVO.list_Param param) throws Exception {
        PageBean<Admin_UserVO> list = getService().list(param);
        return list;
    }

    @Operation(summary = "根据关键字查询")
    @PostMapping("/listByKeyword")
    public List<Admin_UserVO.listByKeyword_Res> listByKeyword(@Valid @RequestBody Admin_UserVO.listByKeyword_Param param) throws Exception {
        List<Admin_UserVO.listByKeyword_Res> list = getService().listByKeyword(param);
        return list;
    }

    @Operation(summary = "更新 用户信息")
    @PostMapping("/operate")
    public BaseAPI.SaveResult<Admin_UserVO> save(@Valid @RequestBody List<Admin_UserVO> param) throws Exception {
        int rows = getService().operate(param);
        BaseAPI.SaveResult result = new BaseAPI.SaveResult();
        result.setRows(rows);
        result.setObject(rows == 0 ? null : param);
        return result;
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public LoginUser login(@Valid @RequestBody Admin_UserVO.login.Param param, HttpServletRequest request) throws Exception {
        // 登录
        long start = System.currentTimeMillis();
        LoginUser loginUser = null;
        Admin_UserVO userVO = null;
        if (StringUtil.isNotEmpty(param.getToken())) { // 使用jwt
            userVO = getService().loginByJwt(param);
        } else  { // 默认使用 session
            userVO = getService().loginBySession(param);
        }
        // 设置用户
        LoginUser.User user = JsonUtil.copyObj(userVO, LoginUser.User.class);
        user.setUserName(userVO.getName());
        loginUser = new LoginUser();
        loginUser.setUserInfo(user);
        loginUser.setToken(StringUtil.isNotEmpty(param.getToken()) ? param.getToken() :JWTUtil.encodeToken(user.getId()));

        // 设置资源
        if (param.isCrtResource()) {
            getService().setResource(user, loginUser);
        }

        // 建立会话
        if (param.isCrtSession()) {
            HttpSession session = request.getSession();
            session.setAttribute(session.getId(), loginUser);
        }

        // 记录日志
        //耗时
        Long spentTime = System.currentTimeMillis()-start;
        final String threadId = (String) MyThreadLocal.getCurrentThread().get(MyThreadLocal.TRACE_ID);
        logTaskHelper.putLog(request, spentTime, threadId);
        return loginUser;
    }

    @Operation(summary = "用户注销")
    @PostMapping("/logout")
    public ResponseObject logout(HttpServletRequest request){
        // 记录日志
        final String threadId = (String) MyThreadLocal.getCurrentThread().get(MyThreadLocal.TRACE_ID);
        logTaskHelper.putLog(request, 1L, threadId);
        // 清空会话
        HttpSession session = request.getSession();
        session.invalidate();
        return ResponseObject.success("user logout success");
    }

}

